package com.hyou.springboot.validator.constraints;

import java.text.ParseException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import com.hyou.springboot.annotation.validator.DateStyle;

/**
 * <pre>
 * 日期格式校验器，实现日期格式的校验逻辑。
 * </pre>
 * 
 * @author FengChangshuo
 * @version 1.0.0 2018-03-28 11:03:22 初始创建
 */
public class DateStyleValidator implements ConstraintValidator<DateStyle, String> {
    
    /**
     * 日期格式。例如：yyyyMMdd
     */
    private String pattern;
    
    @Override
    public void initialize(DateStyle constraintAnnotation) {
        this.pattern = constraintAnnotation.pattern();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        
        if (StringUtils.isBlank(value)) {
            return true;
        }
        
        try {
            DateUtils.parseDate(value, this.pattern);
        } catch (@SuppressWarnings("unused") ParseException e) {
            return false;
        }
        
        return true;
    }
    
}
